package com.easymin.weixin.controller.web;

import com.easymin.weixin.common.geetest.GeetestLib;
import com.easymin.weixin.common.geetest.GeetestMsgConfig;

import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
public class HomeController {
  
  /**
   * 调整登录界面.
   */
  @RequestMapping(value = {"", "/", "login"})
  public String index(HttpServletRequest request, Model model) {

    if (SecurityUtils.getSubject().isAuthenticated()) {

      return "redirect:/home";

    } else {


      GeetestLib gtsdk = new GeetestLib();
      gtsdk.setCaptchaId(GeetestMsgConfig.getCaptcha_id());
      gtsdk.setPrivateKey(GeetestMsgConfig.getPrivate_key());
      gtsdk.setGtSession(request);

      String resStr = null;

      if (gtsdk.preProcess() == 1) {
        // gt server is in use
        resStr = gtsdk.getSuccessPreProcessRes();
        gtsdk.setGtServerStatusSession(request, 1);
      } else {
        // gt server is down
        resStr = gtsdk.getFailPreProcessRes();
        gtsdk.setGtServerStatusSession(request, 0);
      }

      model.addAttribute("captchaId", gtsdk.getCaptchaId());
      model.addAttribute("challengeId", resStr);

      return "login";
    }
  }

  @RequestMapping(value = "home", method = RequestMethod.GET)
  public String home() {

    return "home";
  }
  
  /**
   * 登出.
   */
  @RequestMapping(value = "logout", method = RequestMethod.GET)
  public String logout() {

    if (SecurityUtils.getSubject().isAuthenticated()) {
      SecurityUtils.getSubject().logout();
    }

    return "redirect:/";
  }
}
